package com.br.dnaklass.core;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;

@SuppressWarnings( "rawtypes" )
public class ReflectTools {

	@SuppressWarnings( "unchecked" )
	public static <T> T instance( Class klass ) {
		T object = null;
		try {
			Constructor<?>[] constructors = klass.getConstructors();

			Constructor<?> c = constructors[0];

			if ( c != null ) {
				List<Object> params = new ArrayList<Object>();
				for ( Class<?> type : c.getParameterTypes() ) {
					if ( type.isPrimitive() ) {
						if ( type.equals( int.class ) ) {
							params.add( new Integer( 0 ) );
						} else if ( type.equals( float.class ) ) {
							params.add( new Float( 0 ) );
						} else if ( type.equals( double.class ) ) {
							params.add( new Double( 0.0 ) );
						} else if ( type.equals( char.class ) ) {
							params.add( new Character( '0' ) );
						} else if ( type.equals( long.class ) ) {
							params.add( new Long( 0 ) );
						}
					} else {
						params.add( null );
					}
				}
				object = (T) klass.cast( c.newInstance( params.toArray() ) );
			}

		} catch ( InstantiationException e ) {
			e.printStackTrace();
		} catch ( IllegalAccessException e ) {
			e.printStackTrace();
		} catch ( IllegalArgumentException e ) {
			e.printStackTrace();
		} catch ( InvocationTargetException e ) {
			e.printStackTrace();
		}
		return object;
	}
}
